<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogCompletForm.visible"
    :width="900"
    :title="dialogCompletForm.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="200"
      style="padding-right: 10px; overflow: auto"
    >
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
        >施工许可证信息
      </el-row>
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="formData.projectName" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编号" prop="prjNum">
            <el-input v-model="formData.projectNum" disabled placeholder="自动关联" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工许可证编号" prop="builderLicences">
            <el-input v-model="formData.builderLicences" placeholder="请输入施工许可证编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工许可证发证日期" prop="builderLicencesGrantDate">
            <el-date-picker
              v-model="formData.builderLicencesGrantDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              @change="() => (formData.builderLicencesTermDate = undefined)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="施工许可证有效期限" prop="builderLicencesTermDate">
            <el-date-picker
              v-model="formData.builderLicencesTermDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              :disabled-date="disabledbuilderLicencesTermDate"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        style="border-left: 5px solid #3b98f7; margin-left: 50px; text-indent: 2em; line-height: 30px; font-weight: 600"
        >工程担保信息<el-text type="danger"
          >政府投资项目，担保单位可填写立项审批单位，附件请上传发改批复；社会投资项目请提供资金来源或担保函。</el-text
        >
      </el-row>
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="12">
          <el-form-item label="是否有工程款支付担保" prop="hasEarnestMoney">
            <el-radio-group v-model="formData.hasEarnestMoney">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="12">
          <el-form-item label="担保单位名称" prop="earnestUnitName">
            <el-input v-model="formData.earnestUnitName" placeholder="请输入担保单位名称" />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="12">
          <el-form-item label="担保单位统一社会信用代码" prop="earnestUnitCode">
            <el-input v-model="formData.earnestUnitCode" placeholder="请输入统一社会信用代码" />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="12">
          <el-form-item label="担保金额" prop="earnestMoney">
            <money-input v-model="formData.earnestMoney" placeholder="请输入担保金额" unit="万元"></money-input>
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="12">
          <el-form-item label="担保开始日期" prop="earnestStartDate">
            <el-date-picker
              v-model="formData.earnestStartDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              @change="() => (formData.earnestEndDate = undefined)"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="12">
          <el-form-item label="担保终止日期" prop="earnestEndDate">
            <el-date-picker
              v-model="formData.earnestEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              :disabled-date="disabledEarnestEndDate"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formData.hasEarnestMoney" :span="24">
          <el-form-item label="上传担保文件" prop="earnestAttachments">
            <el-upload
              v-model:file-list="earnestFileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogCompletForm.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import MoneyInput from "@/components/MoneyInput/index.vue";
import { Except, Ride } from "@/utils/decimal";
import { CompleteProjectInfo, GetCompleteProjectForm } from "@/api/project/projectInfo/index";
import { ProjectCompletForm } from "@/api/project/projectInfo/types";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";
import moment from "moment";
import { CheckSocialCreditCode } from "@/utils/verify";

const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

//上传文件列表
const earnestFileList = ref<UploadUserFile[]>([]);

const props = defineProps({
  dialogCompletForm: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
});

const { dialogCompletForm } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectCompletForm>({});
const addOrEditFormRef = ref(ElForm);

/**
 * 施工许可证有效禁用日期
 */
const disabledbuilderLicencesTermDate = (time: Date) => {
  if (formData.builderLicencesGrantDate) {
    return time.getTime() < moment(formData.builderLicencesGrantDate).toDate().getTime();
  }
};

/**
 * 禁用日期
 */
const disabledEarnestEndDate = (time: Date) => {
  if (formData.earnestStartDate) {
    return time.getTime() < moment(formData.earnestStartDate).toDate().getTime();
  }
};

const validatorEarnestAttachment = function (rule: any, value: any, callback: any) {
  if (earnestFileList.value.length == 0) {
    callback(new Error("请上传担保文件附件!"));
    return;
  } else {
    callback();
  }
};

/* 统一社会信用代码检查 */
const SocialCreditCodeBlur = (rule: any, value: any, callback: any) => {
  if (!rule.required) {
    callback();
    return;
  }
  if (!value || value === undefined || value === "") {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  if (value.length < 18) {
    callback("请输入正确的统一社会信用代码");
    return;
  }
  let check = CheckSocialCreditCode(value);
  if (check) {
    callback();
  } else {
    callback("请输入正确的统一社会信用代码");
  }
};
const rules = reactive<FormRules<ProjectCompletForm>>({
  builderLicences: [{ required: true, message: "施工许可证不能为空", trigger: "blur" }],
  builderLicencesGrantDate: [{ required: true, message: "施工许可证发证日期不能为空", trigger: "blur" }],
  builderLicencesTermDate: [{ required: true, message: "施工许可证有效期不能为空", trigger: "blur" }],
  hasEarnestMoney: [{ required: true, message: "请选择是否有工程款支付担保", trigger: "blur" }],
  earnestUnitName: [{ required: true, message: "担保单位名称不能为空", trigger: "blur" }],
  earnestUnitCode: [{ required: true, trigger: "blur", validator: SocialCreditCodeBlur }],
  earnestMoney: [
    { required: true, message: "担保金额不能为空", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          if (value > formData.contractAmount) {
            callback(new Error("担保金额不能大于合同金额" + formData.contractAmount + "万元"));
          } else {
            callback();
          }
        } else {
          callback(new Error("担保金额不能为空"));
        }
      },
    },
  ],
  earnestStartDate: [{ required: true, message: "担保开始日期不能为空", trigger: "blur" }],
  earnestEndDate: [{ required: true, message: "担保终止日期不能为空", trigger: "blur" }],
  earnestAttachments: [
    {
      required: true,
      message: "请上传担保文件",
      trigger: "blur",
      validator: validatorEarnestAttachment,
    },
  ],
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

const initForm = async function () {
  if (dialogCompletForm.value.id) {
    loading.value = true;
    let res = await GetCompleteProjectForm(dialogCompletForm.value.id);
    loading.value = false;
    if (res.type != 0 || !res.success) return;
    res.data.contractAmount = Except(res.data.contractAmount, 10000);
    res.data.earnestMoney = Except(res.data.earnestMoney, 10000);
    if (res.data.earnestAttachments) {
      let list = Array<any>();
      res.data.earnestAttachments.forEach((item: any) => {
        list.push({
          name: item.attachmentName,
          status: "success",
          uid: item.attachmentId,
        });
      });
      earnestFileList.value = list;
      Object.assign(formData, res.data);
    }
  }
};

onMounted(async () => {
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.projectId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (formData.earnestAttachments == undefined) {
        formData.earnestAttachments = new Array();
      }
      earnestFileList.value.forEach((item: any) => {
        if (item.status != "success") return;
        if (item.response) {
          formData.earnestAttachments?.push({
            attachmentId: item.response.data,
          });
        } else {
          formData.earnestAttachments?.push({
            attachmentId: item.uid,
          });
        }
      });

      let submitForm = Object.assign({}, formData);
      submitForm.earnestMoney = Ride(formData?.earnestMoney ?? 0, 10000);
      if (dialogCompletForm.value.id || dialogCompletForm.value.id > 0) {
        CompleteProjectInfo(dialogCompletForm.value.id, submitForm)
          .then((res) => {
            if (res.type != 0 || !res.success) return;
            ElMessage.success(res.msg);
            closeDialog(true);
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
